//
//  DAHomePageShowBookDetailViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/5/11.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAHomePageShowBookDetailViewController.h"
#import "DASameReaderView.h"
#import "DASearchBookDetailModel.h"
#import "DASimilarBook.h"
#import "Utility.h"
#import "DAOtherPersonalViewController.h"

@interface DAHomePageShowBookDetailViewController ()<DASimilarBookDelegate, DASameReaderView>
/** scrollView高度的约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewHeight;
/** 图书的描述Label*/
@property (weak, nonatomic) IBOutlet  DALabel *bookDescription;
/** 所以控件都在bookDetailView上*/
@property (weak, nonatomic) IBOutlet UIView *bookDetailView;

/** 在scrollView上的View 用来固定scrollView*/
@property (weak, nonatomic) IBOutlet UIView *onScrollViewView;
/** 图书描述的内容高度的约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bookDescriptionHeight;
/** "图书描述"这四个字的label  */
@property (weak, nonatomic) IBOutlet DALabel *bookDescriptionLabel;
@property (nonatomic, copy) NSString *str;
/** bookDetailView的高度约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bookDetailHeight;
/** 图书名字的label*/
@property (weak, nonatomic) IBOutlet DALabel *bookNameLabel;
/** 图书作者的label*/
@property (weak, nonatomic) IBOutlet UILabel *bookAuthorLabel;
/** 小星星1*/
@property (weak, nonatomic) IBOutlet UIImageView *starOne;
/** 小星星2*/
@property (weak, nonatomic) IBOutlet UIImageView *starTwo;
/** 小星星3*/
@property (weak, nonatomic) IBOutlet UIImageView *starThree;
/** 小星星4*/
@property (weak, nonatomic) IBOutlet UIImageView *starFour;
/** 小星星5*/
@property (weak, nonatomic) IBOutlet UIImageView *starFive;
/** 图书持有人label*/
@property (weak, nonatomic) IBOutlet UILabel *bookHolderLabel;
/** 图书类型*/
@property (weak, nonatomic) IBOutlet UILabel *bookType;
/** 相关图书的image*/
@property (weak, nonatomic) IBOutlet UIImageView *bookImageView;
/** 看过此书的用户头像*/
@property (weak, nonatomic) IBOutlet UIImageView *userImageView;
/** 评分的view*/
@property (weak, nonatomic) IBOutlet DARateView *rateView;

@property (weak, nonatomic) IBOutlet UILabel *sameReader;

@property (weak, nonatomic) IBOutlet UILabel *similarBook;
/** 读过此书的view */
@property (weak, nonatomic) IBOutlet DASameReaderView *sameReaderView;

@property (nonatomic, strong)  DASearchBookDetailModel *bookDetailModel;

@property (weak, nonatomic) IBOutlet DASimilarBook *similarBookView;

@property (weak, nonatomic) IBOutlet UILabel *similarBookLabel;

@property (weak, nonatomic) IBOutlet UILabel *readerLineLabel;

@property (weak, nonatomic) IBOutlet UILabel *bookLineLabel;
@property (weak, nonatomic) IBOutlet UIView *bookBackView;

@end

@implementation DAHomePageShowBookDetailViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.onScrollViewView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
   // [self prepareData];
}
#pragma mark - 页面配置
- (void)configurationView{
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.backgroundColor = [UIColor whiteColor];
    /** closeImage放到前面 不跟着滚动*/
   // [self.view bringSubviewToFront:self.closeImage];
    [self.view bringSubviewToFront:self.closeImageBackView];
    self.view.layer.cornerRadius = 5;
    self.scrollView.layer.cornerRadius = 5;
    self.view.backgroundColor = [UIColor whiteColor];
    self.bookDetailView.backgroundColor = [UIColor whiteColor];
    self.str = self.bookDetailModel.bookIntro;
    self.bookDescription.font = [UIFont systemFontOfSize:12];
    [self.bookDescription setText:self.str fitToContent:YES];
    self.bookNameLabel.textColor = [UIColor colorWithHexString:bookNameColor];
    self.bookDescription.textColor = [UIColor colorWithHexString:bookNameColor];
    self.readerLineLabel.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.bookLineLabel.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.bookBackView.backgroundColor = [UIColor whiteColor];
}
#pragma mark - 更新约束
- (void)updateViewConstraints{
    [super updateViewConstraints];
    CGFloat height = [self heightWithText:self.str Width:([UIScreen mainScreen].bounds.size.width - 20 ) - 20 - 20 Font:12];
    self.bookDescriptionHeight.constant = height;
    self.bookDetailHeight.constant = 380 + self.bookDescriptionHeight.constant;
    self.scrollViewHeight.constant = self.bookDetailHeight.constant;
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.view = nil ;
    [self.view removeFromSuperview];
}
#pragma mark - 页面配置
- (void)configBookDetailView{
    /** 评分*/
    NSString *rateNum = self.bookDetailModel.bookRate;
    [self.rateView rateNum:rateNum.integerValue];
    [self.rateView setNeedsDisplay];
    self.rateView.backgroundColor = [UIColor whiteColor];
    self.bookType.textColor = [UIColor colorWithHexString:borrowTimeColor];
    self.bookHolderLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
    NSString *sameReaderStr = NSLocalizedString(@"readTheBookPeople", nil);
    self.sameReader.text = sameReaderStr;
    self.sameReader.textColor = [UIColor colorWithHexString:borrowTimeColor];
    self.sameReader.font = [UIFont systemFontOfSize:12];
    NSString *similarBookStr = NSLocalizedString(@"bookSimilar", nil);
    self.similarBookLabel.text = similarBookStr;
    self.similarBookLabel.textColor =[UIColor colorWithHexString:borrowTimeColor];
    self.similarBookLabel.font = [UIFont systemFontOfSize:12];
    self.similarBook.textColor = [UIColor colorWithHexString:borrowTimeColor];
    
    // 设置代理人
    self.sameReaderView.delegate = self;
    [self.sameReaderView  creatReaderUserImageWithArray:self.bookDetailModel.bookSameReader];
    self.sameReaderView.backgroundColor = [UIColor whiteColor];
    
    // 设置代理人
    self.similarBookView.delegate = self;
    [self.similarBookView creatSimilarBookImageWithArray:self.bookDetailModel.similiarBook];
    
    self.similarBookView.backgroundColor = [UIColor whiteColor];
    [self.bookNameLabel setText:self.bookDetailModel.bookName fitToContent:YES];
    NSString *bookType = NSLocalizedString(@"bookType", nil);
    
    self.bookType.text = [NSString stringWithFormat:@"%@: %@", bookType,self.bookDetailModel.bookTypeName];
    NSString *bookSource = NSLocalizedString(@"bookSource", nil);
    self.bookHolderLabel.text = [NSString stringWithFormat:@"%@: %@",bookSource,self.bookDetailModel.bookSourceName];
    self.str = self.bookDetailModel.bookIntro;
    [self updateViewConstraints];
    
    
    // 创建占位图
    UIView *bookCover = [[UIView alloc]initWithFrame:CGRectMake(0 , 0, self.bookImageView.frame.size.width, self.bookImageView.frame.size.height)];
    bookCover.backgroundColor = [UIColor supportGreenColor];
    DALabel *bookCoverName = [[DALabel alloc]initWithFrame:CGRectMake(5, 5, bookCover.frame.size.width -10, bookCover.frame.size.height - 10)];
    [bookCoverName setText:self.bookDetailModel.bookName fitToContent:YES];
    bookCoverName.verticalAlignment = VerticalAlignmentMiddle;
    bookCoverName.textAlignment = NSTextAlignmentCenter;
    [bookCoverName setTextColor:[UIColor whiteColor]];
    bookCoverName.font = [UIFont systemFontOfSize:12];
    [bookCover addSubview:bookCoverName];
    
    UIImage *image = [self.view makeImageWithView:bookCover];
    
    [self.bookImage sd_setImageWithURL:[NSURL URLWithString:self.bookDetailModel.bookImage] placeholderImage:image];
    
    
   // [self.bookImage sd_setImageWithURL:[NSURL URLWithString: self.bookDetailModel.bookImage]];
//    self.bookImage.layer.borderWidth = 1;
//    self.bookImage.layer.borderColor = [UIColor whiteColor].CGColor;
}
// =================================网络请求和数据处理==============================================//
#pragma mark - 数据准备
- (void)prepareData{
     self.view.hidden = YES;
    NSString *url = DABookDetailURL;
    NSDictionary *dic = @{@"bookID": self.bookID,
                          @"userID": self.userID};
    //[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSString *isLoading = NSLocalizedString(@"isLoading", nil);
    [SVProgressHUD showWithStatus:isLoading];
    [self dataHandelWithUrl:url parame:dic];
}
#pragma mark 网络请求
- (void)dataHandelWithUrl:(NSString *)url parame:(NSDictionary *)parame{
    [DADataHandel postURL:url parame:parame cookie:nil result:^(id result) {
        if (result &&[result[@"result"] isKindOfClass:[NSDictionary class]]) {
            [self dataTransformModel:result[@"result"]];
           // NSLog(@"%@", result[@"result"]);
        }else{
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
                if (self.isSelectHomePageTimeLine) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"GRAYVIEWHIDDEN" object:nil];
                }
                if (self.isSelectPersonalPage) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"GRAYVIEWREMOVE" object:nil];
                }
                
                if (self.isSelectOtherPersonalPage) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"GRAYVIEWREMOVESUPERVIEW" object:nil];
                }
                
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
                if (self.isSelectHomePageTimeLine) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"GRAYVIEWHIDDEN" object:nil];
                }
                if (self.isSelectPersonalPage) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"GRAYVIEWREMOVE" object:nil];
                }
                if (self.isSelectOtherPersonalPage) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"GRAYVIEWREMOVESUPERVIEW" object:nil];
                }
            }
            else{
                [SVProgressHUD showErrorWithStatus:self.requestFailed];
                if (self.isSelectHomePageTimeLine) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"GRAYVIEWHIDDEN" object:nil];
                }
                if (self.isSelectPersonalPage) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"GRAYVIEWREMOVE" object:nil];
                }
                if (self.isSelectOtherPersonalPage) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"GRAYVIEWREMOVESUPERVIEW" object:nil];
                }
            }
        }
//        else if ([result isKindOfClass:[NSString class]]){
//            NSLog(@"请求错误");
//            [SVProgressHUD showErrorWithStatus:@"加载错误"];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self finishLoadDataMBProgress];
//            });
//        }
    }];
}
#pragma mark - 数据转model
- (void)dataTransformModel:(NSDictionary *)dic{
    DASearchBookDetailModel *detailBookModel = [[DASearchBookDetailModel alloc]init];
    self.bookDetailModel = [detailBookModel dataTransformModelWith:dic];
    /** 调用配置页面*/
    [self configurationView];
    [self configBookDetailView];
    [self finishLoadDataMBProgress];
    self.view.hidden = NO;
    
    if (self.isSelectHomePageTimeLine) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"VIEWHIDDEN" object:nil];
    }
    NSLog(@"图书编号: %@", dic[@"bookPrivate"]);
}
//=================================== end =======================================================

- (void)dealloc{

}

#pragma mark -类似图书实现代理人协议方法
- (void)similarBookClick:(NSInteger)index{
    self.bookID = self.bookDetailModel.similiarBook[index][@"bookID"];
    [self prepareData];
    [self.scrollView setContentOffset:CGPointMake(0, 0)];
}
#pragma mark -阅读过此书的人 的协议方法
- (void)sameReaderView:(NSInteger)index{
    // 获取userID
    NSString *userID = self.bookDetailModel.bookSameReader[index][@"userID"];
    
    if (self.isSelectHomePageTimeLine) {
        // 发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SendMessageToOtherPersonal" object:userID];
    }
    if (self.isSelectPersonalPage) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TurnPersonalPage" object:userID];
    }
    if (self.isSelectOtherPersonalPage) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"OtherPersonalRefresh" object:userID];
    }
    
    if (self.isSelectMessage) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"MESSAGEDETAILISUSERID" object:userID];
    }
    
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
